package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import tools.OptionReader;
import contacts.CheckboxBook;
import contacts.Person;

/**
 * Erstellt JPanel, welche in die Kontaktansicht/funktion eingefuegt wird
 * 
 * @author frederikroessler
 * 
 */
public class AddContactPane extends JPanel {

	private static final long serialVersionUID = 4301655841374003345L;
	private Connection connection = Test.getConnection();

	// Sprachen (0 = deutsch; 1 = englisch; 2 = latein)

	private int speak = 0;
	private int sorted = 0;

	String[] editbutton = { "Bearbeiten", "Edit", "Incudo" };
	String[] savebutton = { "Speichern", "Save", "Demuto" };

	String[] tooltipAdd = { "Fuegen sie einen neuen Kontakt hinzu.",
			"Add a new contact.", "Addicere addunt novum persona." };
	String[] tooltipDelete = { "Loescht den ihnen angezeigten Kontakt.",
			"Delete the selected contact.", "Errarum delectorum persona." };
	String[] tooltipNext = { "Zeigt den nächsten Kontakt an",
			"Show next contact.", "Ostende proximus huic persona" };
	String[] tooltipLast = { "Zeigt den vorherigen Kontakt an",
			"Show previous contact.", "Ostende previous persona." };
	String[] tooltipAktuell = {
			"Hier wird Ihnen der Name des aktuell ausgewählten Kontaktes angezeit",
			"Show the name of the selected contact.",
			"Ostende nomen delectorum persona." };
	String[] tooltipsort = {"Hier können sie die Sortierung der Kontakte ändern", "Change the way contacts are sorted", "Hic vos potest mutare diribitio"};
	
	
	String[] name = { "Name", "name", "nomen" };
	String[] vorname = { "Vorname", "first name", "praenomen" };
	String[] strasse = { "Strasse", "street", "via" };
	String[] plz = { "PLZ", "postcode", "territorium" };
	String[] stadt = { "Stadt", "street", "oppidum" };
	String[] email = { "E-Mail", "mail", "technicus nuntius" };
	String[] geburtstag = { "Geburtstag", "birthday", "diei natalis" };
	String[] telefonHeim = { "Telefon (Heim)", "phone (home)",
			"telephonum (patria)" };
	String[] telefonArbeit = { "Telefon (Arbeit)", "phone (work)",
			"telephonum (opus)" };
	String[] telefonMobil = { "Telefon (Mobil)", "mobile", "telephonum manuale" };
	String[] telefonFax = { "FAX", "fax", "mutoniatus" };
	String[] Adressbuch = { "Adressbuch", "Adress Book", "index domiciliorum " };
	//

	// Textfelder fuer Detailansicht
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;
	private JTextField textField_5;
	private JTextField textField_6;
	private JTextField textField_7;
	private JTextField textField_8;
	private JTextField textField_9;
	private JTextField textField_10;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;
	private int globalselectedid;
	private JComboBox tag = new JComboBox();
	private JComboBox monat = new JComboBox();
	private JComboBox jahr = new JComboBox();
	private JButton saveButton;
	private JButton kontaktBearbeitenButton;
	private JButton previousKontaktButton;
	private JButton nextKontaktButton;
	private boolean activated = true;
	private JTextField aktuellerKontakt;
	private JComboBox book;
	private LinkedList<CheckboxBook> llbooks = new LinkedList<CheckboxBook>();
	private String[] bookDropdown;
	final DefaultListModel dlm;
	final JList contactlist;
	ResultSet temp;
	private JPanel centerpanel;
	private AddContactPane acp;
	// Liste um Personen intern zu speichern
	private LinkedList<Person> contactlinkedlist = new LinkedList<Person>();
	private ListSelectionListener selectionListener;
	private boolean listselectionactivated = true;

	/**
	 * Gibt RS mit allen Kontakten des Users aus DB zurueck, sortiert nach
	 * Vorname
	 * 
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getContactsFromDb() throws SQLException {

		Statement stat = connection.createStatement();

		// String franz = "'franz'";

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Adress.* FROM Adress, Entrys, Books, User where Adress.idAdress = Entrys.idAdress AND Entrys.idBooks = Books.idBooks AND Books.idUser = User.idUser AND User.idUser="
						+ Test.iduser
						+ " GROUP BY Adress.idAdress ORDER BY Adress.fname;");

		return rs;

	}

	/**
	 * Gibt RS mit allen Kontakten des Users aus DB zurueck, sortiert nach
	 * Nachname
	 * 
	 * @return gibt ResultSet nach namen sortiert
	 * @throws SQLException
	 */
	public ResultSet getContactsFromDbLName() throws SQLException {

		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Adress.* FROM Adress, Entrys, Books, User where Adress.idAdress = Entrys.idAdress AND Entrys.idBooks = Books.idBooks AND Books.idUser = User.idUser AND User.idUser="
						+ Test.iduser
						+ " GROUP BY Adress.idAdress ORDER BY Adress.lname;");

		return rs;

	}

	/**
	 * Holt Kontakte aus der datenbank
	 * 
	 * @param idAdress
	 *            Adressbuch ID des Adressbuches
	 * @return Gibt Result Set mit Kontakten zurück
	 * @throws SQLException
	 */

	public ResultSet getEntrysFromDb(int idAdress) throws SQLException {

		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Entrys.* FROM Entrys where Entrys.idAdress = "
						+ idAdress + ";");

		return rs;

	}

	/**
	 * Gibt Liste zurueck mit zu Adressen zugehöerigen Buechern
	 * 
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public LinkedList<Integer> getAdressIdFromBooks() throws SQLException,
			ClassNotFoundException {

		LinkedList<Integer> adressIds = new LinkedList<Integer>();

		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat.executeQuery("SELECT Entrys.* FROM Entrys");

		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager
				.getConnection("jdbc:sqlite:checkids.db");
		Statement stat2 = conn.createStatement();

		ResultSet rs2 = stat2.executeQuery("select * from ids;");

		LinkedList<Integer> ids = new LinkedList<Integer>();

		while (rs2.next()) {
			ids.add(rs2.getInt("id"));
			System.out.println("test");

		}

		while (rs.next()) {
			int idAdress = rs.getInt("idAdress");
			int idBook = rs.getInt("idBooks");

			for (int i = 0; i < ids.size(); i++) {

				if (ids.get(i) == idBook) {
					adressIds.add(idAdress);
				}

			}
		}

		return adressIds;
	}

	/**
	 * Erstellt JPanel
	 */
	public AddContactPane() {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		speak = Integer.parseInt(or.getLanguage());
		sorted = Integer.parseInt(or.getConOpt1());

		Dimension size = new Dimension(800, 500);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		setBackground(Color.LIGHT_GRAY);
		setLayout(new BorderLayout(0, 0));

		// NEW BUTTON LEISTE

		JPanel buttonPanel = new JPanel();
		buttonPanel.setBackground(new Color(r, g, b));
		buttonPanel.setSize(new Dimension(260, 40));
		buttonPanel.setPreferredSize(new Dimension(260, 40));
		buttonPanel.setMinimumSize(new Dimension(260, 40));
		buttonPanel.setMaximumSize(new Dimension(260, 40));
		add(buttonPanel, BorderLayout.NORTH);
		GridBagLayout gbl_buttonPanel = new GridBagLayout();
		gbl_buttonPanel.columnWidths = new int[] { 80, 40, 40, 40, 40, 40, 40,
				40, 0, 0 };
		gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
		gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
				0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE };
		gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		buttonPanel.setLayout(gbl_buttonPanel);

		/**
		 * Button oeffnet Kontakt hinzufuegen Dialog
		 */
		Icon iconHinzu = new ImageIcon("src/pictures/add.png");
		JButton hinzufuegenButton = new JButton(iconHinzu);
		hinzufuegenButton.setToolTipText(tooltipAdd[speak]);

		hinzufuegenButton.setMaximumSize(new Dimension(40, 40));
		hinzufuegenButton.setMinimumSize(new Dimension(40, 40));
		hinzufuegenButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_button = new GridBagConstraints();
		gbc_button.fill = GridBagConstraints.HORIZONTAL;
		gbc_button.insets = new Insets(0, 0, 0, 5);
		gbc_button.gridx = 0;

		gbc_button.gridy = 0;

		acp = this;

		// Listener fuer Kontakt hinzufuegen Button, hier wird ein neues
		// NewContactWindow erstellt, welches das erstellen von einem neuen
		// Kontakt ermoeglicht
		ActionListener addKontakt = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				setListselectionactivated(false);
				JFrame ncw = new NewContactWindow(acp);
				ncw.setVisible(true);

			}

		};

		hinzufuegenButton.addActionListener(addKontakt);

		buttonPanel.add(hinzufuegenButton, gbc_button);

		/**
		 * Button loescht ausgewaehlten Kontakt
		 */
		Icon iconLoeschen = new ImageIcon("src/pictures/bin.png");
		JButton kontaktEntfernenButton = new JButton(iconLoeschen);
		kontaktEntfernenButton.setToolTipText(tooltipDelete[speak]);
		kontaktEntfernenButton.setPreferredSize(new Dimension(40, 40));
		kontaktEntfernenButton.setMinimumSize(new Dimension(40, 40));
		kontaktEntfernenButton.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_button_1 = new GridBagConstraints();
		gbc_button_1.insets = new Insets(0, 0, 0, 5);
		gbc_button_1.gridx = 1;
		gbc_button_1.gridy = 0;

		ActionListener remove = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

				if (globalselectedid != 0) {
					listselectionactivated = false;
					@SuppressWarnings("rawtypes")
					SwingWorker worker = new SwingWorker() {
						@Override
						public Object doInBackground() {

							Statement stat = null;
							try {
								int i = globalselectedid;
								stat = connection.createStatement();
								stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
								stat.executeUpdate("DELETE FROM `sopra-ws12-awesome_fireballs`.`Adress` WHERE `idAdress`="
										+ i + ";");

							} catch (SQLException e) {
								JOptionPane.showMessageDialog(null,
										"Es konnte keine Verbindung zur Datenbank hergestellt werden",
										"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
							}
							return stat;

						}

						@Override
						public void done() {
								update();

						}
					};
					worker.execute();

				}

			}

		};
		kontaktEntfernenButton.addActionListener(remove);

		buttonPanel.add(kontaktEntfernenButton, gbc_button_1);

		Icon iconEdit = new ImageIcon("src/pictures/edit.png");

		kontaktBearbeitenButton = new JButton(iconEdit);
		kontaktBearbeitenButton.setToolTipText(editbutton[speak]);
		kontaktBearbeitenButton.setMinimumSize(new Dimension(40, 40));
		kontaktBearbeitenButton.setMaximumSize(new Dimension(40, 40));
		kontaktBearbeitenButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnWtl = new GridBagConstraints();
		gbc_btnWtl.insets = new Insets(0, 0, 0, 5);
		gbc_btnWtl.gridx = 2;
		gbc_btnWtl.gridy = 0;

		// Action Listener welcher Textfelder rechts auf Bearbeitbar umstellt
		// und anschließend die Einstellungen speichert
		ActionListener edit = new ActionListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void actionPerformed(ActionEvent e) {
				listselectionactivated = false;

				// String text = (String) e.getActionCommand();

				// if (text.equals(editbutton[speak])) {
				contactlist.setEnabled(false);

				kontaktBearbeitenButton.setEnabled(false);
				saveButton.setEnabled(true);
				previousKontaktButton.setEnabled(false);
				nextKontaktButton.setEnabled(false);
				activated = false;

				// kontaktBearbeitenButton.setText(savebutton[speak]);

				textField.setEditable(true);
				textField_1.setEditable(true);
				textField_2.setEditable(true);
				textField_3.setEditable(true);
				textField_4.setEditable(true);
				book.setEnabled(true);

				// setzt Geburtstag unsichtbar
				textField_5.setVisible(false);

				// macht statdessen Comboboxen für das Datum
				// Datum
				int intjahr = 0;
				int intmonat = 0;
				int inttag = 0;
				String date = textField_5.getText();

				if (date.equals("")) {
					intjahr = -1;
					intmonat = -1;
					inttag = -1;
				} else {
					System.out.println(date);
					String[] values = date.split("\\.");
					System.out.println(values.length);
					System.out.println(Arrays.toString(values));

					intjahr = Integer.parseInt(values[2]) - 1900;
					intmonat = Integer.parseInt(values[1]) - 1;
					inttag = Integer.parseInt(values[0]) - 1;
				}

				// Jahr //
				Date d = new Date();
				int y = d.getYear();

				String[] jahreArray = new String[y + 2];

				jahreArray[0] = "";
				for (int i = 1; i <= y + 1; i++) {
					jahreArray[i] = Integer.toString(i + 1899);

				}

				jahr.removeAllItems();

				for (String s : jahreArray) {
					jahr.addItem(s);
				}

				jahr.setSelectedIndex(intjahr + 1);

				jahr.setBounds(330, 168, 85, 20);
				centerpanel.add(jahr);

				// Monat //
				String[] monatsArray = new String[13];

				monatsArray[0] = "";
				for (int i = 1; i < 13; i++) {
					String s = "";
					if (i < 10) {
						s = "0";
					}
					s += Integer.toString(i);
					monatsArray[i] = s;
				}

				monat.removeAllItems();

				for (String s : monatsArray) {
					monat.addItem(s);
				}

				// removeItem(Object)
				// removeItemAt(int)
				// removeAllItems()
				// und
				// addItem(Object)
				monat.setSelectedIndex(intmonat + 1);

				monat.setBounds(255, 168, 70, 20);
				centerpanel.add(monat);

				// Tag //
				String[] tagesArray = new String[32];

				tagesArray[0] = "";
				for (int i = 1; i < 32; i++) {
					String s = "";
					if (i < 10) {
						s = "0";
					}
					s += Integer.toString(i);
					tagesArray[i] = s;
				}

				tag.removeAllItems();

				for (String s : tagesArray) {
					tag.addItem(s);
				}

				tag.setSelectedIndex(inttag + 1);

				tag.setBounds(180, 168, 70, 20);
				centerpanel.add(tag);

				textField_6.setEditable(true);
				textField_7.setEditable(true);
				textField_8.setEditable(true);
				textField_9.setEditable(true);
				textField_10.setEditable(true);

			}

		};

		kontaktBearbeitenButton.addActionListener(edit);

		buttonPanel.add(kontaktBearbeitenButton, gbc_btnWtl);

		Icon iconSave = new ImageIcon("src/pictures/save.png");
		saveButton = new JButton(iconSave);
		saveButton.setToolTipText(savebutton[speak]);
		saveButton.setPreferredSize(new Dimension(40, 40));
		saveButton.setMinimumSize(new Dimension(40, 40));
		saveButton.setMaximumSize(new Dimension(40, 40));
		saveButton.setEnabled(false);
		GridBagConstraints gbc_btnAnt = new GridBagConstraints();
		gbc_btnAnt.insets = new Insets(0, 0, 0, 5);
		gbc_btnAnt.gridx = 3;
		gbc_btnAnt.gridy = 0;

		ActionListener saveKontakt = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				// if (text.equals(savebutton[speak])) {

				contactlist.setEnabled(true);
				previousKontaktButton.setEnabled(true);
				nextKontaktButton.setEnabled(true);
				kontaktBearbeitenButton.setEnabled(true);
				saveButton.setEnabled(false);
				activated = true;

				textField.setEditable(false);
				textField_1.setEditable(false);
				textField_2.setEditable(false);
				textField_3.setEditable(false);
				textField_4.setEditable(false);
				textField_5.setVisible(true);
				book.setEnabled(false);

				if ((jahr.getSelectedIndex() == 0)
						|| (monat.getSelectedIndex() == 0)
						|| (tag.getSelectedIndex() == 0)) {
					textField_5.setText("");

				} else {
					textField_5.setText(

					String.valueOf((tag.getSelectedIndex())) + "."
							+ String.valueOf((monat.getSelectedIndex())) + "."
							+ String.valueOf((jahr.getSelectedIndex() + 1899)));
				}

				textField_6.setEditable(false);
				textField_7.setEditable(false);
				textField_8.setEditable(false);
				textField_9.setEditable(false);
				textField_10.setEditable(false);

				@SuppressWarnings("rawtypes")
				SwingWorker worker = new SwingWorker() {
					@Override
					public Object doInBackground() {

						Statement stat = null;
						try {
							stat = connection.createStatement();
							// der inhalt der Textfelder wird in Strings
							// gespeichert
							String fname = textField_10.getText();
							String lname = textField.getText();
							String street = textField_1.getText();
							String zip = textField_2.getText();
							String town = textField_3.getText();
							String email = textField_4.getText();

							String bday = "";
							if ((jahr.getSelectedIndex() == 0)
									|| (monat.getSelectedIndex() == 0)
									|| (tag.getSelectedIndex() == 0)) {

							} else {
								bday = String
										.valueOf((jahr.getSelectedIndex() + 1899)
												+ "-"
												+ String.valueOf((monat
														.getSelectedIndex()))
												+ "-"
												+ String.valueOf((tag
														.getSelectedIndex())));

							}
							String telehome = textField_6.getText();
							String telework = textField_7.getText();
							String fax = textField_9.getText();
							String cell = textField_8.getText();

							int selectedBook = book.getSelectedIndex();

							int idBook = llbooks.get(selectedBook).getIdBooks();

							stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

							// es wird ein vorgefertigtes update statement
							// erstellt und anschließen werden in die
							// jeweiligen fragezeichen, die Strings
							// eingefügt.
							connection.setAutoCommit(false);
							PreparedStatement pstmt = connection
									.prepareStatement("UPDATE `sopra-ws12-awesome_fireballs`.`Adress` SET `fname`=?, `lname`=?, `street`=?, `zip`=?, `city`=?, `email`=?, `bday`=?, `telehome`=?, `telework`=?, `fax`=?, `cell`=? WHERE `idAdress`=?;");
							pstmt.setString(1, fname);
							pstmt.setString(2, lname);
							pstmt.setString(3, street);
							pstmt.setString(4, zip);
							pstmt.setString(5, town);
							pstmt.setString(6, email);
							pstmt.setString(7, bday);
							pstmt.setString(8, telehome);
							pstmt.setString(9, telework);
							pstmt.setString(10, fax);
							pstmt.setString(11, cell);
							pstmt.setInt(12, globalselectedid);

							pstmt.addBatch();

							PreparedStatement pstmt2 = connection
									.prepareStatement("UPDATE `sopra-ws12-awesome_fireballs`.`Entrys` SET `idBooks`=? WHERE `idAdress`=?");
							pstmt2.setInt(1, idBook);
							pstmt2.setInt(2, globalselectedid);

							pstmt2.addBatch();

							System.out.println(pstmt.toString());
							// das vorgefertigte statement wird ausgeführt
							pstmt.executeBatch();
							pstmt2.executeBatch();
							connection.commit();
							connection.setAutoCommit(true);
						} catch (SQLException e) {
							JOptionPane.showMessageDialog(null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
							e.printStackTrace();
						}
						return stat;

					}

					@Override
					public void done() {
						// kontaktBearbeitenButton.setText(editbutton[speak]);

						ResultSet contacts = null;

						getContactlinkedlist().clear();
						dlm.clear();
						try {
							// Holt ResultSet mit allen Kontakten aus DB
							if (sorted == 0) {
								contacts = getContactsFromDb();
							}
							if (sorted == 1) {
								contacts = getContactsFromDbLName();
							}
							LinkedList<Integer> adressIds = getAdressIdFromBooks();

							while (contacts.next()) {

								// Erstellt fuer jede Person Person Objekt
								// um dieses in
								// conactlinkeslist weiter zu speichern um
								// fuer Personen
								// Detailinformationen zu nutzen
								Person person = new Person(
										contacts.getString("lname"),
										contacts.getString("fname"));
								person.setUserID(contacts.getString("idAdress"));

								int idAdress = contacts.getInt("idAdress");

								// Fuegt alle Personen interner Liste zu um
								// spaeter wieder auf
								// id
								// zurueckgreifen zu koennen.
								for (int j = 0; j < adressIds.size(); j++) {
									if (adressIds.get(j) == idAdress) {
										getContactlinkedlist().add(person);

										// Fuegt String mit name der Person
										// in Liste
										// ein
										dlm.addElement(person.toString());

									}
								}

							}
							temp = contacts;
							listselectionactivated = true;

						} catch (SQLException e) {
							JOptionPane.showMessageDialog(null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				};
				worker.execute();

			}
			// }

		};

		saveButton.addActionListener(saveKontakt);

		buttonPanel.add(saveButton, gbc_btnAnt);

		/**
		 * Sort Button
		 */
		JButton sortButton = new JButton("SORT");
		sortButton.setToolTipText(tooltipsort[speak]);
		sortButton.setPreferredSize(new Dimension(40, 40));
		sortButton.setMinimumSize(new Dimension(40, 40));
		sortButton.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnAntall = new GridBagConstraints();
		gbc_btnAntall.insets = new Insets(0, 0, 0, 5);
		gbc_btnAntall.gridx = 4;
		gbc_btnAntall.gridy = 0;
		sortButton.setEnabled(false);
		sortButton.setVisible(false);

		ActionListener switchSort = new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				if (sorted == 0) {
					sorted = 1;
					update();

				} else if (sorted == 1) {
					sorted = 0;
					update();
				}

			}
		};

		sortButton.addActionListener(switchSort);

		buttonPanel.add(sortButton, gbc_btnAntall);

		/**
		 * Previous Kontakt Button
		 */
		Icon iconBack = new ImageIcon("src/pictures/last.png");

		previousKontaktButton = new JButton(iconBack);
		previousKontaktButton.setToolTipText(tooltipLast[speak]);
		previousKontaktButton.setMaximumSize(new Dimension(40, 40));
		previousKontaktButton.setMinimumSize(new Dimension(40, 40));
		previousKontaktButton.setPreferredSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnLeft = new GridBagConstraints();
		gbc_btnLeft.insets = new Insets(0, 0, 0, 5);
		gbc_btnLeft.gridx = 6;
		gbc_btnLeft.gridy = 0;

		MouseListener getPrev = new MouseAdapter() {

			public void mouseClicked(MouseEvent arg0) {
				if (activated) {
					int aktuell = contactlist.getSelectedIndex();

					contactlist.setSelectedIndex(aktuell - 1);
				}

			}
		};

		previousKontaktButton.addMouseListener(getPrev);

		buttonPanel.add(previousKontaktButton, gbc_btnLeft);

		aktuellerKontakt = new JTextField();
		aktuellerKontakt.setToolTipText(tooltipAktuell[speak]);
		GridBagConstraints gbc_textField = new GridBagConstraints();
		gbc_textField.insets = new Insets(0, 0, 0, 5);
		gbc_textField.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField.gridx = 7;
		gbc_textField.gridy = 0;
		buttonPanel.add(aktuellerKontakt, gbc_textField);
		aktuellerKontakt.setToolTipText(tooltipAktuell[speak]);
		aktuellerKontakt.setDisabledTextColor(new Color(0, 0, 0));
		aktuellerKontakt.setEnabled(false);
		aktuellerKontakt.setEditable(false);
		aktuellerKontakt.setColumns(10);

		/**
		 * Next Task Button
		 */

		Icon iconForward = new ImageIcon("src/pictures/next.png");
		nextKontaktButton = new JButton(iconForward);
		nextKontaktButton.setToolTipText(tooltipNext[speak]);
		nextKontaktButton.setPreferredSize(new Dimension(40, 40));
		nextKontaktButton.setMinimumSize(new Dimension(40, 40));
		nextKontaktButton.setMaximumSize(new Dimension(40, 40));
		GridBagConstraints gbc_btnRight = new GridBagConstraints();
		gbc_btnRight.gridx = 8;
		gbc_btnRight.gridy = 0;

		MouseListener getNext = new MouseAdapter() {

			public void mouseClicked(MouseEvent arg0) {
				if (activated) {
					int aktuell = contactlist.getSelectedIndex();

					contactlist.setSelectedIndex(aktuell + 1);
				}

			}
		};

		nextKontaktButton.addMouseListener(getNext);

		buttonPanel.add(nextKontaktButton, gbc_btnRight);

		/**
		 * LINKES PANEL MIT KONTAKTLISTE WIRD ERSTELLT
		 */
		JPanel westpanel = new JPanel();
		westpanel.setSize(280, 500);
		add(westpanel, BorderLayout.WEST);

		// JList welche Kontakt beinhaltet, hier keine Checkbox noetig, da keine
		// Kontakte hinzugefuegt werden koennen/muessen
		contactlist = new JList();
		// final CheckBoxList contactlist = new CheckBoxList();
		contactlist.setVisibleRowCount(26);
		// contactlist.setSize(280, 500);
		dlm = new DefaultListModel();

		// Verbindung zur Datenbank herstellen

		ResultSet contacts = null;
		try {
			// Holt ResultSet mit allen Kontakten aus DB
			if (sorted == 0) {
				contacts = getContactsFromDb();
			}
			if (sorted == 1) {
				contacts = getContactsFromDbLName();
			}
			LinkedList<Integer> adressIds = getAdressIdFromBooks();

			while (contacts.next()) {

				// Erstellt fuer jede Person Person Objekt um dieses in
				// conactlinkeslist weiter zu speichern um fuer Personen
				// Detailinformationen zu nutzen

				Person person = new Person(contacts.getString("lname"),
						contacts.getString("fname"));
				person.setUserID(contacts.getString("idAdress"));

				int idAdress = contacts.getInt("idAdress");

				// System.out.println(contacts.getString("idAdress"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.

				for (int i = 0; i < adressIds.size(); i++) {
					if (adressIds.get(i) == idAdress) {
						getContactlinkedlist().add(person);

						// Fuegt String mit name der Person in Liste ein
						dlm.addElement(person.toString());
					}

				}

			}

			// String test = "";
			// for (int i = 0; i < contactlinkedlist.size(); i++) {
			//
			// test = test + contactlinkedlist.get(i).toString();
			//
			// }
			//
			// System.out.println(test);
			
			temp = contacts;

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		

		// Listener, welche bei Klicken auf Listenobjekt, die zugehoerigen
		// Detailinformationen der Person in die jeweiligen Textfelder einfuegt
		selectionListener = new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {

				if (getListselectionactivated() == true) {

					int index = contactlist.getSelectedIndex();

					// Findet UserId von aktuell gewaehltem Kontakt aus der
					// Liste
					String userid = getContactlinkedlist().get(index)
							.getUserID();
					globalselectedid = Integer.parseInt(userid);

					aktuellerKontakt.setText(getContactlinkedlist().get(index)
							.toString());
					aktuellerKontakt.setCaretPosition(0);

					// System.out.println(userid);

					int useridint = Integer.parseInt(userid);

					try {

						temp.absolute(1);

						ResultSet entrys = getEntrysFromDb(useridint);

						if (temp.getInt("idAdress") == useridint) {
							textField.setText(temp.getString("lname"));
							textField_10.setText(temp.getString("fname"));
							textField_1.setText(temp.getString("street"));
							textField_2.setText(temp.getString("zip"));
							textField_3.setText(temp.getString("city"));
							textField_4.setText(temp.getString("email"));

							// // Dreht den String von Date um. ////
							String sd = temp.getString("bday");
							String ds = "";

							if ((sd != null)) {
								String[] values = sd.split("-");
								if (values.length == 3) {
									// Setzt Nullen vor die einstelligen
									// Monatszahlen
									String nullString3 = "";
									String nullString4 = "";
									if (values[2].length() == 1) {
										nullString3 = "0";
									}
									if (values[1].length() == 1) {
										nullString4 = "0";
									}
									ds = nullString3 + values[2] + "."
											+ nullString4 + values[1] + "."
											+ values[0];
								}
							}

							textField_5.setText(ds);

							textField_6.setText(temp.getString("telehome"));
							textField_7.setText(temp.getString("telework"));
							textField_8.setText(temp.getString("cell"));
							textField_9.setText(temp.getString("fax"));

							Statement stat;

							stat = connection.createStatement();
							stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

							ResultSet idsBooks = stat
									.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
											+ Test.iduser + ";");
							while (idsBooks.next()) {

								CheckboxBook temp = new CheckboxBook(
										idsBooks.getInt("idBooks"),
										idsBooks.getString("name"),
										idsBooks.getInt("idCreator"));

								llbooks.add(temp);
							}

							String posName = "";

							while (entrys.next()) {
								System.out.println("ID BOOK: "
										+ entrys.getInt("idBooks"));
								for (int i = 0; i < llbooks.size(); i++) {

									if (llbooks.get(i).getIdBooks() == entrys
											.getInt("idBooks")) {
										posName = llbooks.get(i).getName();
									}
								}
							}

							for (int i = 0; i < bookDropdown.length; i++) {
								if (bookDropdown[i].equals(posName)) {

								}
							}

							book.setEnabled(true);
							book.setSelectedItem(posName);

							book.setEnabled(false);

						}

						while (temp.next()) {

							// System.out.println(temp.getInt("idAdress"));
							if (temp.getInt("idAdress") == useridint) {

								// System.out.println(temp.getInt("idAdress"));

								// Setzt alle Textfelder auf die verfuegbaren
								// Infos des
								// Kontaktes
								textField.setText(temp.getString("lname"));
								textField_10.setText(temp.getString("fname"));
								textField_1.setText(temp.getString("street"));
								textField_2.setText(temp.getString("zip"));
								textField_3.setText(temp.getString("city"));
								textField_4.setText(temp.getString("email"));

								// // Dreht den String von Date um. ////
								String sd2 = temp.getString("bday");
								String ds2 = "";

								if ((sd2 != "")) {
									String[] values = sd2.split("-");
									if (values.length == 3) {

										// Setzt Nullen vor die einstelligen
										// Monatszahlen
										String nullString = "";
										String nullString2 = "";
										if (values[2].length() == 1) {
											nullString = "0";
										}
										if (values[1].length() == 1) {
											nullString2 = "0";
										}
										ds2 = nullString + values[2] + "."
												+ nullString2 + values[1] + "."
												+ values[0];
									}

								}

								textField_5.setText(ds2);

								// textField_5.setText(temp.getString("bday"));
								textField_6.setText(temp.getString("telehome"));
								textField_7.setText(temp.getString("telework"));
								textField_8.setText(temp.getString("cell"));
								textField_9.setText(temp.getString("fax"));

								Statement stat;

								stat = connection.createStatement();
								stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

								ResultSet idsBooks = stat
										.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
												+ Test.iduser + ";");
								while (idsBooks.next()) {

									CheckboxBook temp = new CheckboxBook(
											idsBooks.getInt("idBooks"),
											idsBooks.getString("name"),
											idsBooks.getInt("idCreator"));

									llbooks.add(temp);
								}

								String posName = "";

								entrys.absolute(1);

								System.out.println("ID BOOK: "
										+ entrys.getInt("idBooks"));
								for (int i = 0; i < llbooks.size(); i++) {

									if (llbooks.get(i).getIdBooks() == entrys
											.getInt("idBooks")) {
										posName = llbooks.get(i).getName();
									}
								}

								for (int i = 0; i < bookDropdown.length; i++) {
									if (bookDropdown[i].equals(posName)) {

									}
								}

								book.setEnabled(true);
								book.setSelectedItem(posName);

								book.setEnabled(false);

							}
						}

						// temp.absolute(useridint);
						// System.out.println(temp.getString("idAdress"));

					} catch (SQLException e1) {
						JOptionPane.showMessageDialog(null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
						e1.printStackTrace();
					}

				}

			}

		};

		// Fuegt dlm und Listener an Liste
		contactlist.setModel(dlm);
		contactlist.addListSelectionListener(selectionListener);

		// Liste in scrollpane und scrollpane in linkes Panel
		JScrollPane scrollPane = new JScrollPane(contactlist);
		scrollPane.setPreferredSize(new Dimension(280, 570));

		westpanel.add(scrollPane);

		/**
		 * RECHTS PANEL MIT DETAILANSICHT WIRD ERSTELLT
		 */
		// TODO
		centerpanel = new JPanel();
		centerpanel.setBackground(new Color(r, g, b));
		add(centerpanel, BorderLayout.CENTER);
		centerpanel.setLayout(null);

		// JLabel zu allen Textfeldern werden erstellt
		JLabel lblName = new JLabel(name[speak]);
		lblName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblName.setBounds(50, 30, 117, 16);
		centerpanel.add(lblName);

		JLabel lblStrae = new JLabel(strasse[speak]);
		lblStrae.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStrae.setBounds(50, 58, 117, 16);
		centerpanel.add(lblStrae);

		JLabel lblPlz = new JLabel(plz[speak]);
		lblPlz.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPlz.setBounds(50, 86, 117, 16);
		centerpanel.add(lblPlz);

		JLabel lblStadt = new JLabel(stadt[speak]);
		lblStadt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStadt.setBounds(50, 114, 117, 16);
		centerpanel.add(lblStadt);

		JLabel lblEmail = new JLabel(email[speak]);
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(50, 142, 117, 16);
		centerpanel.add(lblEmail);

		JLabel lblGeburtstag = new JLabel(geburtstag[speak]);
		lblGeburtstag.setHorizontalAlignment(SwingConstants.RIGHT);
		lblGeburtstag.setBounds(50, 170, 117, 16);
		centerpanel.add(lblGeburtstag);

		JLabel lblTelefonheim = new JLabel(telefonHeim[speak]);
		lblTelefonheim.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonheim.setBounds(50, 198, 117, 16);
		centerpanel.add(lblTelefonheim);

		JLabel lblTelefonarbeit = new JLabel(telefonArbeit[speak]);
		lblTelefonarbeit.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonarbeit.setBounds(50, 226, 117, 16);
		centerpanel.add(lblTelefonarbeit);

		JLabel lblFax = new JLabel(telefonFax[speak]);
		lblFax.setHorizontalAlignment(SwingConstants.RIGHT);
		lblFax.setBounds(50, 282, 117, 16);
		centerpanel.add(lblFax);

		JLabel lblTelefonmobil = new JLabel(telefonMobil[speak]);
		lblTelefonmobil.setHorizontalAlignment(SwingConstants.RIGHT);
		lblTelefonmobil.setBounds(40, 254, 127, 16);
		centerpanel.add(lblTelefonmobil);

		JLabel lblVorname = new JLabel(vorname[speak]);
		lblVorname.setBounds(309, 30, 71, 16);
		centerpanel.add(lblVorname);

		JLabel adressbuch = new JLabel(Adressbuch[speak]);
		adressbuch.setHorizontalAlignment(SwingConstants.RIGHT);
		adressbuch.setBounds(50, 307, 117, 16);
		centerpanel.add(adressbuch);

		// Textfelder werden erstellt

		// Name
		textField = new JTextField();
		textField.setBounds(180, 24, 117, 28);
		centerpanel.add(textField);
		textField.setColumns(10);
		textField.setEditable(false);

		// Strasse
		textField_1 = new JTextField();
		textField_1.setBounds(180, 52, 344, 28);
		centerpanel.add(textField_1);
		textField_1.setColumns(10);
		textField_1.setEditable(false);

		// PLZ
		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(180, 80, 344, 28);
		centerpanel.add(textField_2);
		textField_2.setEditable(false);

		// Stadt
		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(180, 108, 344, 28);
		centerpanel.add(textField_3);
		textField_3.setEditable(false);

		// Email
		textField_4 = new JTextField();
		textField_4.setColumns(10);
		textField_4.setBounds(180, 136, 344, 28);
		centerpanel.add(textField_4);
		textField_4.setEditable(false);

		// Geb
		textField_5 = new JTextField();
		textField_5.setColumns(10);
		textField_5.setBounds(180, 164, 344, 28);
		centerpanel.add(textField_5);
		textField_5.setEditable(false);

		// Tele Heim
		textField_6 = new JTextField();
		textField_6.setColumns(10);
		textField_6.setBounds(180, 192, 344, 28);
		centerpanel.add(textField_6);
		textField_6.setEditable(false);

		// Tele Arbeit
		textField_7 = new JTextField();
		textField_7.setColumns(10);
		textField_7.setBounds(180, 220, 344, 28);
		centerpanel.add(textField_7);
		textField_7.setEditable(false);

		// Tele Mobil
		textField_8 = new JTextField();
		textField_8.setColumns(10);
		textField_8.setBounds(180, 248, 344, 28);
		centerpanel.add(textField_8);
		textField_8.setEditable(false);

		// Fax
		textField_9 = new JTextField();
		textField_9.setColumns(10);
		textField_9.setBounds(180, 276, 344, 28);
		centerpanel.add(textField_9);
		textField_9.setEditable(false);

		// Vorname
		textField_10 = new JTextField();
		textField_10.setBounds(382, 24, 142, 28);
		centerpanel.add(textField_10);
		textField_10.setColumns(10);
		textField_10.setEditable(false);

		Statement stat;
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet idsBooks = stat
					.executeQuery("SELECT idBooks, name, idCreator FROM Books WHERE idUser = "
							+ Test.iduser + ";");
			while (idsBooks.next()) {

				CheckboxBook temp = new CheckboxBook(
						idsBooks.getInt("idBooks"), idsBooks.getString("name"),
						idsBooks.getInt("idCreator"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llbooks.add(temp);

			}
		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}

		bookDropdown = new String[llbooks.size()];
		for (int i = 0; i < llbooks.size(); i++) {
			bookDropdown[i] = llbooks.get(i).getName();
		}

		book = new JComboBox(bookDropdown);

		book.setBounds(180, 307, 344, 28);
		book.setVisible(true);
		centerpanel.add(book);
		book.setEnabled(false);

	}

	// Additional Methods

	/**
	 * erneuert die Elemente in den Listen
	 */
	public void update() {
		listselectionactivated = false;
		contactlist.setEnabled(false);
		dlm.clear();
		contactlinkedlist.clear();

		ResultSet contacts = null;
		try {
			// Holt ResultSet mit allen Kontakten aus DB
			if (sorted == 0) {
				contacts = getContactsFromDb();
			}
			if (sorted == 1) {
				contacts = getContactsFromDbLName();
			}
			LinkedList<Integer> adressIds = getAdressIdFromBooks();

			while (contacts.next()) {

				// Erstellt fuer jede Person Person Objekt um dieses in
				// conactlinkeslist weiter zu speichern um fuer Personen
				// Detailinformationen zu nutzen

				Person person = new Person(contacts.getString("lname"),
						contacts.getString("fname"));
				person.setUserID(contacts.getString("idAdress"));

				int idAdress = contacts.getInt("idAdress");

				// System.out.println(contacts.getString("idAdress"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.

				for (int i = 0; i < adressIds.size(); i++) {
					if (adressIds.get(i) == idAdress) {
						getContactlinkedlist().add(person);

						// Fuegt String mit name der Person in Liste ein
						dlm.addElement(person.toString());
					}

				}

			}

		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		temp = contacts;
		contactlist.setEnabled(true);
		listselectionactivated = true;

	}

	/**
	 * Methode skaliert Bilder effizienter
	 * 
	 * @param ret
	 *            Bild das Skaliert werden soll
	 * @param w
	 *            Breite die das Bild danach haben soll
	 * @param h
	 *            Höhe die das Bild danach haben wird
	 * @return skaliertes Bild mit den Werten w und h
	 */
	public Image resize(Image ret, int w, int h) {

		BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = tmp.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.drawImage(ret, 0, 0, w, h, null);
		g2.dispose();
		return tmp;
	}

	public void setContactlinkedlist(LinkedList<Person> contactlinkedlist) {
		this.contactlinkedlist = contactlinkedlist;
	}

	public LinkedList<Person> getContactlinkedlist() {
		return contactlinkedlist;
	}

	public boolean getListselectionactivated() {
		return listselectionactivated;
	}

	public void setListselectionactivated(boolean listselectionactivated) {
		this.listselectionactivated = listselectionactivated;
	}

	public void forceRepaint() {
		paint(getGraphics());
	}

}
